var Drawer = (function ($, Mzr) {

    'use strict';

    function whichTransitionEvent(){
        var t;
        var el = document.createElement('fakeelement');
        var transitions = {
          'transition':'transitionend',
          'OTransition':'oTransitionEnd',
          'MozTransition':'transitionend',
          'WebkitTransition':'webkitTransitionEnd'
        }

        for(t in transitions){
            if( el.style[t] !== undefined ){
                return transitions[t];
            }
        }
    }

    var transEndEventName = whichTransitionEvent();

    var _body = $('body'),
        _container = $('#container'),
        _overlay = $('.drawer-overlay');

    var module = {
        open: function() {
          _body.addClass('drawer-open drawer-transition');
        },
        close: function() {
          _body.removeClass('drawer-open');
        },
        isOpen: function() {
          return _body.hasClass('drawer-open');
        },
        bindOverlay: function() {
          //console.log("overlay", _overlay);
          _overlay.on('click', function(e) {
            e.preventDefault();

            if(_body.hasClass('drawer-open')) {
              module.close();
            }
          });
        },
        bindAnchors: function() {
          $('.drawer-list a').on('click', function(e) {
            //console.log("drawer-list a clicked");
            module.close();
          });
        },
        bindContainerTransEnd: function() {
          _container.on(transEndEventName, function(e) {
            //console.log("transEnd")
            if(!_body.hasClass('drawer-open')) {
              _body.removeClass('drawer-transition');
            }
          });
        },
        init: function() {
          module.bindOverlay();
          module.bindAnchors();
          module.bindContainerTransEnd();
        }
    };

    return {
      init: module.init,
      open: module.open,
      close: module.close,
      isOpen: module.isOpen
    };

}(jQuery));
